from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from random import randint
from django_redis import get_redis_connection
from server.libs.yuntongxun.sms import CCP
from rest_framework.response import Response
import logging
from rest_framework import status
from . import constants
from celery_tasks.sms.tasks import send_sms_code

logger = logging.getLogger('django')

class SMSCodeView(APIView):
    """短信验证"""
    def get(self, request, mobile):
        redis_conn = get_redis_connection('verify_codes')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        # pl.get('send_flag_%s' % moblie)
        # send_flag = pl.execute()[0]
        if send_flag:
            return Response({'message': '手机号频繁发送短信'},status=status.HTTP_400_BAD_REQUEST)
        sms_code = '%06d' % randint(0,999999)
        logger.info(sms_code)

        pl = redis_conn.pipeline()
        # redis_conn = get_redis_connection('verify_codes')
        pl.setex('sms_%s' % mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)

        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # redis_conn.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()
        # 客户的服务器请求 容联云服务器   多用户会高并发 导致阻塞 要用到celery 解决高并发
        # CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60], 1)

        #触发异步任务 异步任务添加到celery 任务队列
        # send_sms_code(mobile, sms_code)
        #触发异步celery
        send_sms_code.delay(mobile, sms_code)

        return Response({'message': 'ok'})
